<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card shadow="never" :body-style="contentViewHeight">
          <el-tag closable size="small" style="margin-bottom:5px" v-if="selectFileDeviceName" :disable-transitions="false" >
            {{ selectFileDeviceName }}
          </el-tag>
          <el-row :gutter="5">
            <el-col :span="20">
              <el-input
                placeholder="输入关键字进行过滤"
                size="small"
                v-model="filterText">
              </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="refreshTreeNode"  size="small" icon="el-icon-refresh" circle></el-button>
            </el-col>
          </el-row>
            <el-tree
              class="filter-tree"
              :data="partDeviceTreeData"
              :props="{
                value: 'id', // ID字段名
                label: function(data, node) {
                        return  '[' + data.code + ']' + data.name
                }, // 显示名称
                children: 'children', // 子级字段名
                isLeaf: function(data, node) { //该节点是否为叶节点
                  if (data.level == 5) {
                    return true
                  }
                  return false
                }
              }"
              node-key="id"
              lazy
              :load="loadNode"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              :accordion="true"
              highlight-current
              @node-click="handleNodeClick"
              :render-content="renderContent"
              ref="partDeviceTree"
            >
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card  shadow="never" :body-style="contentViewHeight">
          <el-tabs type="border-card" v-model="activeTabName" ref="tabs" @tab-click="handleTabClick">
            <el-tab-pane label="基本信息" name="basicdataPicUploadForm" v-if="['1', '2'].indexOf(this.partDevice.level) >= 0" >
              <BasicdataPicUploadForm ref="basicdataPicUploadForm" :partDevice="partDevice"></BasicdataPicUploadForm>
            </el-tab-pane>
            <el-tab-pane label="设备维修技术标准" name="basicdataRepairList"  v-if="this.partDevice.level == '3'">
               <BasicdataRepairList ref="basicdataRepairList" :partDevice="partDevice"></BasicdataRepairList>
            </el-tab-pane>
            <el-tab-pane label="设备点检标准"  name="check" v-if="this.partDevice.level == '3'">
               <BasicdataCheckStandardMainList ref='check' name="设备点检标准" :partDevice="partDevice"></BasicdataCheckStandardMainList>
            </el-tab-pane>
            <el-tab-pane label="设备维修作业标准" name="repairOperation" v-if="this.partDevice.level == '3'">
              <BasicdataWordUploadList ref='repairOperation' :partDevice="partDevice" :docType="1"></BasicdataWordUploadList>
            </el-tab-pane>
            <el-tab-pane label="设备给油脂标准" name="pickOil" v-if="this.partDevice.level == '3'">
              <BasicdataGiveOilMainFormList ref="pickOil" :partDevice="partDevice"></BasicdataGiveOilMainFormList>
            </el-tab-pane>
            <el-tab-pane label="设备使用维护规程" name="maintenance" v-if="this.partDevice.level == '3'" >
               <BasicdataWordUploadList ref='maintenance' :partDevice="partDevice" :docType="2"></BasicdataWordUploadList>
            </el-tab-pane>
            <el-tab-pane label="油品检化验标准" name="oilTest" v-if="this.partDevice.level == '3'" >
              <BasicdataOilCheckStanarrdList ref='oilTest' :partDevice="partDevice"></BasicdataOilCheckStanarrdList>
            </el-tab-pane>
            <el-tab-pane label="设备档案" name="archives" v-if="this.partDevice.level == '3'">
              <BasicdataWordUploadList ref='archives' :partDevice="partDevice" :docType="3"></BasicdataWordUploadList>
            </el-tab-pane>
            <el-tab-pane label="图纸" name="drawing" v-if="['3', '4', '5'].indexOf(this.partDevice.level) >= 0">
              <BasicdataWordUploadList ref='drawing' :partDevice="partDevice" :docType="4"></BasicdataWordUploadList>
            </el-tab-pane>
            <el-tab-pane label="技术协议" name="agreement" v-if="['3', '4', '5'].indexOf(this.partDevice.level) >= 0">
              <BasicdataWordUploadList ref='agreement' :partDevice="partDevice" :docType="5"></BasicdataWordUploadList>
            </el-tab-pane>
           </el-tabs>
           </el-card>
       </el-col>
    </el-row>
  </div>
</template>
<script>
import BasicdataPicUploadForm from '../standard/BasicdataPicUploadForm' // 图片管理模块
import BasicdataWordUploadList from '../standard/BasicdataWordUploadList' // 文档管理模块
import BasicdataRepairList from '../standard/BasicdataRepairList' // 设备维修技术标准模块
import BasicdataOilCheckStanarrdList from '../standard/BasicdataOilCheckStanarrdList' // 油品点检化验标准
import BasicdataGiveOilMainFormList from '../standard/BasicdataGiveOilMainFormList'  // 设备给油脂标准
import BasicdataCheckStandardMainList from '../standard/BasicdataCheckStandardMainList' // 设备点检标准
export default {
  data () {
    return {
      partDevice: {
        id: '', // 当前树节点的设备id
        code: '',
        name: '', // 设备名称
        level: '',  // 设备层级
        parents: [] // 设备的所有祖先，第一个为根节点，如果当前节点为根节点，则parents.length===0
      },
      activeTabName: 'ss',  // tabs中当前激活的tab名字
      filterText: '',
      partDeviceTreeData: [],
      selectFileDeviceName: '',
      isSearchCollapse: false,
      isImportCollapse: false,
      loading: false
    }
  },
  components: {
    BasicdataPicUploadForm, // 图片管理模块
    BasicdataWordUploadList, // 文档管理模块
    BasicdataRepairList, // 设备维修技术标准模块
    BasicdataOilCheckStanarrdList, // 油品点检化验标准
    BasicdataCheckStandardMainList, // 设备点检标准
    BasicdataGiveOilMainFormList
  },
  activated () {
    // this.initTreeData()
  },
  computed: {
    contentViewHeight () {
      let height = this.$store.state.common.documentClientHeight - 122
      return { minHeight: height + 'px' }
    }
  },
  watch: {
    // 监控tabs中当前的激活的tab，每次tab激活则触发数据刷新
    activeTabName: {
      handler (currentTabName, oldTabName) {
        if (currentTabName !== '') {
          console.log('activeTabName值改变了，当前值：' + currentTabName + '，原来值:' + oldTabName)
          this.refreshTabData(currentTabName)
        }
      },
      immediate: true // 第一次绑定数据时就触发
    },
    // 监控左侧树当前节点的变化
    'partDevice.id': {
      handler (newPartDeviceId, oldPartDeviceId) {
        console.log('partDeviceId值改变了,当前值：' + newPartDeviceId + '，原来值:' + oldPartDeviceId)
        /* 等待tabs加载完成，设置默认激活页
        如果之前选中的tab，下次点击中还有，则继续显示
        否则显示第一个标签页 */
        if (this.$refs.tabs) {
          this.$refs.tabs.$nextTick(() => {
            let tabList = []
            for (let t in this.$refs.tabs.panes) {
              tabList.push(this.$refs.tabs.panes[t]._props.name)
            }
            console.log('tabs加载完成')
            if (tabList.indexOf(this.$refs.tabs.currentName) !== -1 && newPartDeviceId.length === oldPartDeviceId.length) {
              // 如果不换层，则不更换tab的焦点
              let tmp = this.activeTabName
              this.activeTabName = ''
              this.activeTabName = tmp
            } else {
              this.activeTabName = ''
              this.activeTabName = tabList[0]
            }
            this.refreshTabData(this.activeTabName)
          })
        }
      },
      immediate: true // 第一次绑定数据时就触发
    },
    filterText (val) {
      this.$refs.partDeviceTree.filter(val)
    }
  },
  methods: {
    /**
     * 懒加载树
     * @param {Object} node
     * @param {Object} resolve
     */
    loadNode (node, resolve) {
      if (node.level <= 5) {
        this.getTreeData(node, resolve)
      }
    },
    /**
     * 获取树数据
     * @param {Object} node
     * @param {Object} resolve
     */
    getTreeData (node, resolve) {
      this.$http({
        url: `/basicdata/basictree/partDeviceNode/nextLevelTreeData`,
        method: 'get',
        params: {
          id: node.data.id
        }
      }).then(({ data }) => {
        if (node.data.runState === '0') {
            for (let count in data.data) {
              data.data[count].runState = '0'
            }
        }
        resolve(data.data)
      })
    },
    refreshTreeNode () {
    },
    renderContent (h, { node, data, store }) {
      // el-icon-error el-icon-question
      if (data.runState === '1') {
        return (
          <span class="my-tree-node">
            <i class="el-icon-success success"></i>
            <span>{node.label}</span>
          </span>
        )
      } else if (data.runState === '0') {
        return (
          <span class="my-tree-node">
            <i class="el-icon-warning danger" ></i>
            <span>{node.label}</span>
          </span>
        )
      } else {
        return (
          <span class="my-tree-node">
            <span class="el-icon-question warning"></span><span>{node.label}</span>
          </span>
        )
      }
    },
    /**
     * @param {Object} name tab标签的名字，tab的name需要等于Component的ref
     */
    refreshTabData (name) {
      console.log('刷新组件' + name + '数据...')
      if (this.$refs[name]) {
         this.$refs[name].refreshList()
      }
    },
    /**
     * tab页点击处理，变更activeTabName数据，触发activeTabName的watch
     * @param {Object} tab tab标签
     * @param {Object} event
     */
    handleTabClick (tab, event) {
      this.activeTabName = tab.name
    },
    /**
     * 计算当前节点数据
     * @param {Object} node
     */
    computeCurrentPartDevice (node) {
      this.partDevice.id = node.data.id
      this.partDevice.code = node.data.code
      this.partDevice.name = node.data.name
      this.partDevice.level = node.data.level
      this.partDevice.parents = this.getNodeAncestorsList(node)
      console.log('封装的当前节点partDevice信息：')
      console.log(this.partDevice)
    },
    /**
     * 设置当前节点为选中
     * @param {Object} node
     */
    setHighLight (node) {
      // this.$refs.partDeviceTree.setCurrentKey(node.data.deviceId)
    },
    /**
     * 取得当前节点的所有祖先数据，第一个是根节点。。。爷爷节点、最后一个是父节点
     * @param {Object} node 树的节点的node数据，注意不是节点的data，来源是tree的回调传参
     */
    getNodeAncestorsList (node) {
      let nodeAncestorsList = []
      node = node.parent
      while (node && node.level > 0) {
        nodeAncestorsList.push(node)
        node = node.parent
      }
      return nodeAncestorsList.reverse()
    },
    /**
     * 树节点点击处理
     * @param {Object} data 节点数据
     * @param {Object} node 节点对象
     */
    handleNodeClick (data, node) {
      this.computeCurrentPartDevice(node)
      this.setHighLight(node)
      // this.activeTabName = '' // 每次更换node需将activeTabName重置为''
      this.selectFileDeviceName = '已选: ' + data.name
    },
    filterNode (value, data) {
      if (!value) return true
      return ('[' + data.code + ']' + data.name).indexOf(value) !== -1
    }
  }
}
</script>
<style>
  .my-tree-node {
      display: block;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-pack: justify;
      -ms-flex-pack: justify;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
  }
  .success {
      padding-right: 4px;
      color: #67C23A;
  }
  .danger {
      padding-right: 4px;
      color: #f56c6c;
  }
  .warning {
      padding-right: 4px;
      color: #909399;
  }
</style>
